// createAnswer
// addStream
const {desktopCapturer, ipcRenderer} = window.require('electron')

ipcRenderer.on('offer', async (e, offer) => {
    async function createAnswer(offer) {
        const screenStream = await getScreenStream()
        pc.addStream(screenStream)
        // let res = pc.addTrack(screenStream)
        await pc.setRemoteDescription(offer);
        await pc.setLocalDescription(await pc.createAnswer())
        console.log('answer:', JSON.stringify(pc.localDescription));
        return pc.localDescription
    }

    window.createAnswer = createAnswer
    createAnswer(offer).then(answer => {
        ipcRenderer.send('forward', 'answer', {type: answer.type, sdp: answer.sdp})
    })

    async function getScreenStream() {
        try {
            const sources = await desktopCapturer.getSources({types: ['screen']})
            return new Promise((resolve, reject) => {
                navigator.webkitGetUserMedia({
                    audio: false,
                    video: {
                        mandatory: {
                            chromeMediaSource: 'desktop',
                            chromeMediaSourceId: sources[0].id,
                            maxWidth: window.screen.width,
                            maxHeight: window.screen.height,
                        }
                    }
                }, stream => {
                    resolve(stream)
                }, error => {
                    reject(error)
                    console.log(error)
                })
            })
        } catch (e) {
            console.log('err:', e)
        }
    }

    const pc = new window.RTCPeerConnection({})

    pc.onicecandidate = function (e) {
        // console.log('candidate:', JSON.stringify(e.candidate))
        if (e.candidate) // 告知其他人
            ipcRenderer.send('forward', 'puppet-candidate', JSON.parse(JSON.stringify(e.candidate)))
    }

    pc.ondatachannel = e => {
        console.log('dataChannel', e)
        e.channel.onmessage = e => {
            const {type, data} = JSON.parse(e.data)
            if (type === 'mouse') {
                data.screen = {
                    width: window.screen.width,
                    height: window.screen.height
                }
            }
            ipcRenderer.send('robot', type, data)
        }
    }

    ipcRenderer.on('candidate', async (e, candidate) => {
        console.log('candidate:::',candidate)
        await addIceCandidate(candidate)
    })

    async function addIceCandidate(candidate) {
        if (!candidate) {
            return
        }
        await pc.addIceCandidate(new RTCIceCandidate(candidate))
    }

    window.addIceCandidate = addIceCandidate

})
